package com.ruyichuxing.eyepetizer;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import com.jakewharton.rxbinding.support.v4.widget.RxSwipeRefreshLayout;
import com.jakewharton.rxbinding.support.v7.widget.RxRecyclerView;
import com.ruyichuxing.api.DailyApi;
import com.ruyichuxing.base.ToolbarActivity;
import com.ruyichuxing.model.Category;
import com.ruyichuxing.model.Daily;
import com.ruyichuxing.rx.ErrorAction;
import com.ruyichuxing.rx.RxScroller;
import com.ruyichuxing.widget.InteressantFactory;
import com.ruyichuxing.widget.Register;

import me.drakeet.multitype.Items;
import me.drakeet.multitype.MultiTypeAdapter;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class MainActivity extends ToolbarActivity
		implements NavigationView.OnNavigationItemSelectedListener {

	public static final String PROVIDER_ITEM = "item";
	public static final String CATEGORY_ID = "categoryId";
	public static final String TITLE = "title";

	private SwipeRefreshLayout refreshLayout;
	private RecyclerView list;
	private FloatingActionButton fab;
	private Toolbar toolbar;
	private DrawerLayout drawer;
	private NavigationView navigationView;
	private DailyApi dailyApi;
	private MultiTypeAdapter adapter;
	private Items items = new Items();
	private String dateTime = "";


	@Override
	public int getLayoutId() {
		return R.layout.activity_main;
	}

	@Override
	protected void initView() {

		refreshLayout = (SwipeRefreshLayout) findViewById(R.id.refreshLayout);
		drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
		list = (RecyclerView) findViewById(R.id.list);
		toolbar = (Toolbar) findViewById(R.id.toolbar);
		fab = (FloatingActionButton) findViewById(R.id.fab);
		navigationView = (NavigationView) findViewById(R.id.nav_view);
		ab.setHomeAsUpIndicator(R.drawable.ic_menu);
	}


	@Override
	protected void initData() {


		dailyApi = InteressantFactory.getRetrofit().createApi(DailyApi.class);

		setupRecyclerView();

		RxSwipeRefreshLayout.refreshes(refreshLayout)
				.compose(bindToLifecycle())
				.subscribe(aVoid ->loadData(true));


	}

	private void setupRecyclerView() {
		final LinearLayoutManager layoutManager = new LinearLayoutManager(this);
		adapter = new MultiTypeAdapter(items);
		Register.registerItem(adapter, this);

		list.setLayoutManager(layoutManager);
		list.setAdapter(adapter);

		list.setOnTouchListener((v, event) -> refreshLayout.isRefreshing());

		RxRecyclerView.scrollStateChanges(list)
				.filter(integer -> !refreshLayout.isRefreshing())
				.compose(bindToLifecycle())
				.compose(RxScroller.scrollTransformer(layoutManager,
						adapter, items))
				.subscribe(newState -> {
					if (newState == RecyclerView.SCROLL_STATE_IDLE) {
						loadData();
					}
				});
	}

	private void loadData() {
		loadData(false /*Load more data. */);
	}


	private void loadData(final boolean clear) {
		Observable<Daily> result;
		if (clear) result = dailyApi.getDaily();
		else result = dailyApi.getDaily(Long.decode(dateTime));

		result.compose(bindToLifecycle())
				.filter(daily -> daily != null)
				.doOnNext(daily -> {
					if (clear) items.clear();
				})
				.subscribeOn(Schedulers.io())
				.observeOn(AndroidSchedulers.mainThread())
				.doAfterTerminate(() -> refreshLayout.setRefreshing(false))
				.subscribe(this::addData, ErrorAction.errorAction(this));
	}


	private void addData(Daily daily) {
		for (Daily.IssueList issueList : daily.issueList) {
			String date = issueList.itemList.get(0).data.text;
			items.add(new Category(date == null ? "Today" : date));
			items.addAll(issueList.itemList);
		}
		String nextPageUrl = daily.nextPageUrl;
		dateTime = nextPageUrl.substring(nextPageUrl.indexOf("=") + 1,
				nextPageUrl.indexOf("&"));
		adapter.notifyDataSetChanged();
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

//		requestWindowFeature(Window.FEATURE_NO_TITLE);// 无标题
//		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);// 竖屏
//		setSupportActionBar(toolbar);


		fab.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
						.setAction("Action", null).show();
			}
		});

		DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
		ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
				this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
		drawer.setDrawerListener(toggle);
		toggle.syncState();

		NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
		navigationView.setNavigationItemSelectedListener(this);
	}


	@Override
	protected void onPostCreate(@Nullable Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);
		loadData(true);
	}

	@Override
	public void onBackPressed() {
		DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
		if (drawer.isDrawerOpen(GravityCompat.START)) {
			drawer.closeDrawer(GravityCompat.START);
		} else {
			super.onBackPressed();
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.menu_main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		if (item.getItemId() == R.id.action_settings) {
			drawer.openDrawer(GravityCompat.START);
			return true;
		} else if (item.getItemId() == R.id.search_action) {

			toSearch(this);
		}
		return super.onOptionsItemSelected(item);
	}

	@SuppressWarnings("StatementWithEmptyBody")
	@Override
	public boolean onNavigationItemSelected(MenuItem item) {
		// Handle navigation view item clicks here.
		int id = item.getItemId();

		if (id == R.id.nav_camera) {
			// Handle the camera action
		} else if (id == R.id.nav_gallery) {

		} else if (id == R.id.nav_slideshow) {

		} else if (id == R.id.nav_manage) {

		} else if (id == R.id.nav_share) {

		} else if (id == R.id.nav_send) {

		}

		DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
		drawer.closeDrawer(GravityCompat.START);
		return true;
	}
}
